<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  website
 */

class m_website_services_MenuService extends f_core_Service
{
	/**
	 * @var m_website_services_MenuService
	 */
	private static $instance;
	private $menu;
	private $menuItems;
	
	/**
	 * Constructor
	 */
	private function __construct()
	{
		// Code if needed...
	}
	
	/**
	 * @return m_website_services_MenuService
	 */
	public static function getInstance()
	{
		if (self::$instance === null)
		{
			self::$instance = new self();
		}
		return self::$instance;
	}
		
	public function getMenu($menuId, $menuLang, $depth = null, $level = 0, $currentPage = null, $activeParent = false)
	{	
		$level++;

        if($depth == '0' || $depth == 0) $depth = null;

		$relationManager = f_relation_Manager::getInstance();
		
		$menu = $this->getDocumentProvider()->getByUniqueId($menuId, $menuLang);

        $parentIds = array();
        if(!is_null($currentPage) && $currentPage->getModel() == 'modules_website/page' && $activeParent == true)
        {
            $parentsIds = $relationManager->getParentsIdsByDocType($currentPage->getUniqueId(),  array("modules_website/menu", "modules_website/page", "modules_backoffice/alias"), null, null, null, true);
        }

		echo "\n".'<ul class="menuClass_'.$menuId.'" id="item_'.$menuId.'">'."\n";
		
		$childs = $relationManager->getChildsByDocType($menuId, array("modules_website/menu", "modules_website/page", "modules_backoffice/alias"), $menuLang, array("relation_order"=> "ASC"), 'PUBLISHED');

        $nbChilds = count($childs);

		if($nbChilds > 0)
		{
            foreach($childs as $k => $child)
            {
                if($child->getDocumentModel() == 'modules_backoffice/alias')
                {
                    /* @var $child m_backoffice_documents_Alias */
                    $child = $child->getOriginalDocument();
                }

                if($child->getDocumentModel() == "modules_website/page")
                {
                    if(!$child->isVisibleInMenu() || !$child->isAuthorized($this->getUser()))
                    {
                        unset($childs[$k]);
                    }
                }

                if($child->getDocumentModel() == "modules_website/menu")
                {
                    if(!$child->isVisibleInMenu())
                    {
                        unset($childs[$k]);
                    }
                    else
                    {
                        if(!is_null($child->getMenuPageId()) && $child->getMenuPageId() != '0')
                        {
                            $page = $this->getDocumentProvider()->getByUniqueId($child->getMenuPageId(), $menuLang);
                            if(!$page->isAuthorized($this->getUser()))
                            {                                                                                    
                                unset($childs[$k]);
                            }
                        }
                    }
                }
            }
        }

        $childs = array_values($childs);

        $nbChilds = count($childs);

		if($nbChilds > 0)
		{
			foreach($childs as $k => $child)
			{
                $extClass = '';

                $extClass = ' level'.$level;

                if($k == 0)
                {
                    $extClass .= ' first';
                }

                if($k+1 == $nbChilds)
                {
                    $extClass .= ' last';
                }

                if($activeParent && in_array($child->getUniqueId(), $parentsIds))
                {
                     $extClass .= ' active';
                }

                if($child->getDocumentModel() == 'modules_backoffice/alias')
                {
                    /* @var $child m_backoffice_documents_Alias */
                    $child = $child->getOriginalDocument();
                }

                if($child->getDocumentModel() == "modules_website/page")
                {
                    if(!is_null($currentPage) && $currentPage->getModel() == 'modules_website/page')
                    {
                        if($child->getUniqueId() == $currentPage->getUniqueId())
                        {
                            $extClass .= ' active';
                        }
                    }

                    $completeUrl = $child->getCompleteUrl() == "" ? "/" : $child->getCompleteUrl();
                    echo sprintf('<li class="%s" id="%s"><a href="%s" title="%s">%s</a></li>'."\n", "item_".($k+1).$extClass ,"item_".$menu->getUniqueId()."_".$child->getUniqueId(),$completeUrl, $child->getMenuHoverLabel(), $child->getMenuLabel());
                }

                if($child->getDocumentModel() == "modules_website/menu")
                {
                    ob_start();
                    if(is_null($depth) || $level < $depth)
                    {
                        $this->getMenu($child->getUniqueId(), $child->getLang(), $depth, $level);
                    }
                    $menuHtml = ob_get_clean();

                    $hasIndex = false;
                    if(!is_null($child->getMenuPageId()) && $child->getMenuPageId() != '0')
                    {
                        $page = $this->getDocumentProvider()->getByUniqueId($child->getMenuPageId(), $menuLang);
                        if(!is_null($currentPage) && $currentPage->getModel() == 'modules_website/page')
                        {
                            if($page->getUniqueId() == $currentPage->getUniqueId())
                            {
                               $extClass .= ' active';
                            }
                        }
                        $hasIndex = true;

                        $completeUrl = $page->getCompleteUrl() == "" ? "/" : $page->getCompleteUrl();
                        echo sprintf('<li class="%s" id="%s"><a href="%s" title="%s">%s</a>'."\n", "item_".($k+1).$extClass,"item_".$child->getUniqueId()."_".$page->getUniqueId(),$completeUrl, $child->getMenuHoverLabel(), $child->getMenuLabel());
                    }
                    else
                    {
                        if($menuHtml != '')
                        {
                            echo "\n"."<li>".$child->getLabel().$menuHtml;
                        }
                    }

                    if($menuHtml != '' || $hasIndex == true)
                    {
                        echo "\n"."</li>";
                    }
                }
            }
		}
		
		echo "\n".'</ul>';
	}
	
	public function getMenuChildItems($parentDoc, $onlyMenus = false, $showMenuWoIndex = false)
	{
		$relManager = f_relation_Manager::getInstance();
		$documentProvider = f_document_Provider::getInstance();	
		
		$items = array();
				
		if(is_object($parentDoc))
		{
			$itemIds = $relManager->getChildsIdsByDocType($parentDoc->getUniqueId(), array("modules_website/menu", "modules_website/page"), $parentDoc->getLang(), array("relation_order" => "ASC"));

			foreach($itemIds as $itemId)
			{
				$document = $documentProvider->getByModelAndUniqueId($itemId['child_model'], $itemId['child_id'], $itemId['lang']);

				if($document->getPublicationStatus() == "PUBLISHED" && $document->getUrl() != '')
				{
					if($onlyMenus == false && $document->getDocumentModel() == "modules_website/page")
					{
						if($document->isVisibleInMenu())
						{
							$items[] = $document;
						}
					}
					else
					{
						if($document->isVisibleInMenu())
						{
							if($showMenuWoIndex == true || !is_null($document->getMenuPageId()))
							{
								$items[] = $document;
							}
						}
					}
				}
			}			
		}

		return $items;
	}	
}